const db = require('../config/db.config.js');

// 获取活动列表
exports.getAllEvents = async (req, res) => {
  try {
    const [events] = await db.query('SELECT * FROM Events');
    res.json(events);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 创建活动（管理员权限）
exports.createEvent = async (req, res) => {
  try {
    const { name, description, location, date, image_path } = req.body;
    console.log('\n=== 创建活动开始 ===');
    console.log('1. 接收到的数据:', {
      name,
      description,
      location,
      date,
      image_path,
    });

    const formattedDate = new Date(date).toISOString().split('T')[0];
    console.log('2. 格式化后的日期:', formattedDate);

    const imageUrlJson = image_path
      ? JSON.stringify([`/uploads/events/${image_path}`])
      : null;
    console.log('3. 构建的图片URL:', imageUrlJson);

    const sql =
      'INSERT INTO Events (name, description, location, date, image_url) VALUES (?, ?, ?, ?, ?)';
    const params = [name, description, location, formattedDate, imageUrlJson];
    console.log('4. SQL语句:', sql);
    console.log('5. SQL参数:', params);

    const [result] = await db.query(sql, params);
    console.log('6. 数据库返回结果:', result);

    const [inserted] = await db.query('SELECT * FROM Events WHERE id = ?', [
      result.insertId, // 直接使用result.insertId
    ]);

    res.status(201).json({
      message: '活动创建成功',
      eventId: result.insertId, // 这里也要改
      debug: {
        result: result,
        inserted: inserted[0],
        imageUrl: imageUrlJson,
      },
    });
    console.log('=== 创建活动完成 ===\n');
  } catch (error) {
    console.error('创建活动失败:', error);
    console.error('错误堆栈:', error.stack);
    res.status(500).json({
      message: '服务器错误',
      details: error.sqlMessage || error.message,
    });
  }
};

// 报名活动
exports.registerForEvent = async (req, res) => {
  try {
    const { eventId } = req.body;
    const userId = req.user.id;

    // 检查活动是否已开始
    const [events] = await db.query(
      'SELECT * FROM Events WHERE id = ? AND date > NOW()',
      [eventId]
    );

    if (events.length === 0) {
      return res.status(400).json({ message: '活动已开始或不存在' });
    }

    // 检查是否已报名
    const [existing] = await db.query(
      'SELECT * FROM Event_Registrations WHERE user_id = ? AND event_id = ?',
      [userId, eventId]
    );

    if (existing.length > 0) {
      return res.status(400).json({ message: '已经报名过该活动' });
    }

    await db.query(
      'INSERT INTO Event_Registrations (user_id, event_id) VALUES (?, ?)',
      [userId, eventId]
    );

    res.status(201).json({ message: '活动报名成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除活动（管理员权限）
exports.deleteEvent = async (req, res) => {
  const connection = await db.getConnection();

  try {
    await connection.beginTransaction();
    const { eventId } = req.params;

    // 先检查活动是否存在
    const [event] = await connection.query(
      'SELECT id FROM events WHERE id = ?',
      [eventId]
    );

    if (event.length === 0) {
      await connection.rollback();
      return res.status(404).json({ message: '活动不存在' });
    }

    // 先删除关联的报名记录
    console.log('正在删除报名记录...');
    await connection.query(
      'DELETE FROM event_registrations WHERE event_id = ?',
      [eventId]
    );
    console.log('报名记录删除成功');

    // 再删除活动本身
    console.log('正在删除活动...');
    await connection.query('DELETE FROM events WHERE id = ?', [eventId]);
    console.log('活动删除成功');

    await connection.commit();
    res.json({ message: '活动删除成功' });
  } catch (error) {
    await connection.rollback();
    console.error('删除活动失败:', error);
    res.status(500).json({
      message: '删除失败',
      details: error.sqlMessage || error.message,
    });
  } finally {
    connection.release();
  }
};

// 获取带报名状态的活动列表
exports.getEventsWithRegistration = async (req, res) => {
  try {
    const userId = req.user.id;
    // 先获取所有活动
    const [events] = await db.query('SELECT * FROM Events');
    // 获取用户的报名记录
    const [registrations] = await db.query(
      'SELECT event_id FROM Event_Registrations WHERE user_id = ?',
      [userId]
    );
    // 将报名状态添加到活动数据中
    const registeredEventIds = registrations.map((reg) => reg.event_id);
    const eventsWithRegistration = events.map((event) => ({
      ...event,
      isRegistered: registeredEventIds.includes(event.id),
    }));

    res.json(eventsWithRegistration);
  } catch (error) {
    console.error('获取活动列表失败:', error);
    res.status(500).json({ message: '获取活动列表失败' });
  }
};

// 获取用户的活动记录
exports.getUserEvents = async (req, res) => {
  try {
    const userId = req.user.id;

    const [events] = await db.query(
      `
      SELECT e.id, e.name, e.description, e.location, e.date
      FROM Events e
      INNER JOIN Event_Registrations er ON e.id = er.event_id
      WHERE er.user_id = ?
      ORDER BY e.date DESC
    `,
      [userId]
    );

    // 处理活动状态
    const now = new Date();
    const eventsWithStatus = events.map((event) => {
      const eventDate = new Date(event.date);
      let status;
      if (eventDate < now) {
        status = 'ended';
      } else {
        status = 'upcoming';
      }
      return { ...event, status };
    });

    res.json(eventsWithStatus);
  } catch (error) {
    console.error('获取用户活动记录失败:', error);
    res.status(500).json({ message: '获取活动记录失败' });
  }
};

// 更新活动
exports.updateEvent = async (req, res) => {
  try {
    const eventId = req.params.eventId;
    const { name, description, location, date, image_path } = req.body;
    console.log('更新活动，接收到的图片名称:', image_path);

    // 构建图片URL
    const imageUrlJson = image_path
      ? JSON.stringify([`/uploads/events/${image_path}`])
      : null;
    console.log('更新活动，构建的图片URL:', imageUrlJson);

    const [result] = await db.query(
      'UPDATE Events SET name = ?, description = ?, location = ?, date = ?, image_url = ? WHERE id = ?',
      [name, description, location, date, imageUrlJson, eventId]
    );

    console.log('数据库更新结果:', result);

    if (result[0].affectedRows === 0) {
      return res.status(404).json({ message: '活动不存在' });
    }

    res.json({ message: '活动更新成功' });
  } catch (error) {
    console.error('更新活动失败:', error);
    res.status(500).json({ message: '更新活动失败' });
  }
};

// 取消点赞活动
exports.unlikeEvent = async (req, res) => {
  try {
    const eventId = req.params.eventId;
    const userId = req.user.id;

    await db.query(
      'DELETE FROM Likes WHERE user_id = ? AND content_type = ? AND content_id = ?',
      [userId, 'event', eventId]
    );

    res.json({ message: '取消点赞成功' });
  } catch (error) {
    console.error('取消点赞失败:', error);
    res.status(500).json({ message: '取消点赞失败' });
  }
};

// 取消收藏活动
exports.unfavoriteEvent = async (req, res) => {
  try {
    const eventId = req.params.eventId;
    const userId = req.user.id;

    await db.query(
      'DELETE FROM Favorites WHERE user_id = ? AND content_type = ? AND content_id = ?',
      [userId, 'event', eventId]
    );

    res.json({ message: '操作成功' });
  } catch (error) {
    console.error('取消收藏失败:', error);
    res.status(500).json({ message: '取消收藏失败' });
  }
};

// 获取活动详情（包含点赞和收藏状态）
exports.getEventDetail = async (req, res) => {
  try {
    const eventId = req.params.eventId;
    const userId = req.user?.id;

    let query = `
      SELECT e.*, 
        COUNT(DISTINCT l.id) as likes_count,
        COUNT(DISTINCT f.id) as favorites_count,
        MAX(CASE WHEN l2.id IS NOT NULL THEN 1 ELSE 0 END) as is_liked,
        MAX(CASE WHEN f2.id IS NOT NULL THEN 1 ELSE 0 END) as is_favorited
      FROM Events e
      LEFT JOIN Likes l ON e.id = l.content_id AND l.content_type = 'event'
      LEFT JOIN Favorites f ON e.id = f.content_id AND f.content_type = 'event'
      LEFT JOIN Likes l2 ON e.id = l2.content_id AND l2.content_type = 'event' AND l2.user_id = ?
      LEFT JOIN Favorites f2 ON e.id = f2.content_id AND f2.content_type = 'event' AND f2.user_id = ?
      WHERE e.id = ?
      GROUP BY e.id
    `;

    const [events] = await db.query(query, [userId, userId, eventId]);

    if (events[0].length === 0) {
      return res.status(404).json({ message: '活动不存在' });
    }

    // 生成分享URL
    const shareUrl = `${process.env.FRONTEND_URL}/event/${eventId}`;
    events[0].share_url = shareUrl;

    // 解析图片URL JSON，如果存在的话
    if (events[0].image_url && typeof events[0].image_url === 'string') {
      try {
        events[0].image_url = JSON.parse(events[0].image_url);
      } catch (error) {
        console.error('解析图片URL失败:', error);
        events[0].image_url = null;
      }
    }

    res.json(events[0]);
  } catch (error) {
    console.error('获取活动详情失败:', error);
    res.status(500).json({ message: '获取活动详情失败' });
  }
};

// 点赞活动
exports.likeEvent = async (req, res) => {
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();
    const eventId = req.params.eventId;
    const userId = req.user.id;

    // 检查是否已点赞
    const [existing] = await connection.query(
      'SELECT * FROM Likes WHERE user_id = ? AND content_id = ? AND content_type = "event"',
      [userId, eventId]
    );

    if (existing.length > 0) {
      // 取消点赞
      await connection.query(
        'DELETE FROM Likes WHERE user_id = ? AND content_id = ? AND content_type = "event"',
        [userId, eventId]
      );
      await connection.query(
        'UPDATE Events SET likes_count = likes_count - 1 WHERE id = ?',
        [eventId]
      );
      await connection.commit();
      return res.json({ message: '取消点赞成功', liked: false });
    }

    // 添加点赞
    await connection.query(
      'INSERT INTO Likes (user_id, content_id, content_type) VALUES (?, ?, "event")',
      [userId, eventId]
    );
    await connection.query(
      'UPDATE Events SET likes_count = likes_count + 1 WHERE id = ?',
      [eventId]
    );

    await connection.commit();
    res.json({ message: '点赞成功', liked: true });
  } catch (error) {
    await connection.rollback();
    console.error('活动点赞失败:', error);
    res.status(500).json({ message: '操作失败' });
  } finally {
    connection.release();
  }
};

// 收藏活动
exports.favoriteEvent = async (req, res) => {
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();
    const eventId = req.params.eventId;
    const userId = req.user.id;

    // 检查是否已收藏
    const [existing] = await connection.query(
      'SELECT * FROM Favorites WHERE user_id = ? AND content_id = ? AND content_type = "event"',
      [userId, eventId]
    );

    if (existing.length > 0) {
      // 取消收藏
      await connection.query(
        'DELETE FROM Favorites WHERE user_id = ? AND content_id = ? AND content_type = "event"',
        [userId, eventId]
      );
      await connection.query(
        'UPDATE Events SET favorites_count = favorites_count - 1 WHERE id = ?',
        [eventId]
      );
      await connection.commit();
      return res.json({ message: '操作成功', favorited: false });
    }

    // 添加收藏
    await connection.query(
      'INSERT INTO Favorites (user_id, content_id, content_type) VALUES (?, ?, "event")',
      [userId, eventId]
    );
    await connection.query(
      'UPDATE Events SET favorites_count = favorites_count + 1 WHERE id = ?',
      [eventId]
    );

    await connection.commit();
    res.json({ message: '操作成功', favorited: true });
  } catch (error) {
    await connection.rollback();
    console.error('活动收藏失败:', error);
    res.status(500).json({ message: '操作失败' });
  } finally {
    connection.release();
  }
};

// 获取活动列表
exports.getEvents = exports.getAllEvents;
